﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using KingCat_Socket;
using System.Threading;
using CaptureScreen;
using System.Net.Sockets;
using System.Net;
using System.Media;
using System.IO;
using System.Runtime.InteropServices;
using MyMp3Baby;

namespace KingCat_Client
{
    public partial class ChatRoom : Form
    {
        /// <summary>
        /// 接收服务器信息
        /// </summary>
        private Thread _thread1;
        /// <summary>
        /// Udp服务是否已经启动
        /// </summary>
        private Boolean flag = false;
        /// <summary>
        /// 播放消息提示的播放器
        /// </summary>
        private string path = "";
        private SoundPlayer _sp;
        private SoundPlayer _sp2;
        /// <summary>
        /// 保存现在的聊天信息，在查看聊天历史的时候用
        /// </summary>
        private string tempChatInfo;
        Boolean flag1 = false;
        /// <summary>
        /// 设置选择的人
        /// </summary>
        private string clid;
        /// <summary>
        /// 设置是否已经点击了表情
        /// </summary>
        private Boolean flag5 = false;
        /// <summary>
        /// 判断用户是否已经选择了接收人
        /// </summary>
        private Boolean flag6 = false;
        /// <summary>
        /// 表情的标示号
        /// </summary>
        private string pictureName;
        /// <summary>
        /// 是否有发送表情
        /// </summary>
        private Boolean hasPicture;
        /// <summary>
        /// 发送表情
        /// </summary>
        private static int sel=0;
        public ChatRoom()
        {
            InitializeComponent();
            DisplaySettingsChanged();
            richTextBox4.Text = "";
            this.Text = this.Text + "   用户名:" + Login.userName;
            this.comboBox1.SelectedIndex = 0;
            statusBarPanel7.Text = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList[0].ToString();
            statusBarPanel6.Text = ConnectServerSocket.getInstance().getServerIpAndPort().Address.ToString();
            statusBarPanel8.Text = ConnectServerSocket.getInstance().getServerIpAndPort().Port.ToString();
            //设置发送消息的快捷键
            this.AcceptButton = button2;
            //初始化音乐
            path = Directory.GetCurrentDirectory();
            path = path.Substring(0, path.LastIndexOf("\\"));
            path = path.Substring(0, path.LastIndexOf("\\"));
            _sp = new SoundPlayer(path + "\\Resources\\msg.wav");
            _sp2 = new SoundPlayer(path + "\\Resources\\nudge.wav");
            //初始化tabPage
            richTextBox2.ReadOnly = true;
            richTextBox3.ReadOnly = true;
            richTextBox2.BackColor = Color.White;
            richTextBox3.BackColor = Color.White;
            //初始化listView
            this.listView_chateronline.BackColor = System.Drawing.SystemColors.Info;
            this.listView_chateronline.ForeColor = System.Drawing.Color.BlueViolet;
            this.listView_chateronline.LargeImageList = this.imageList_head;
            this.listView_chateronline.Name = "listView_chateronline";
            this.listView_chateronline.SmallImageList = this.imageList_head;
            this.listView_chateronline.TabIndex = 1;
            this.listView_chateronline.BackColor = Color.White;
            this.listView_chateronline.UseCompatibleStateImageBehavior = false;
            this.listView_chateronline.View = System.Windows.Forms.View.Details;
            //初始化ListView1
            listView1.Visible = false;
            for (int i = 0; i < 87; i++)
            {
                listView1.Items.Add("", i);
            }
            //标志Udp服务器是否已经启动
            Boolean flag = false;
            //加载群公告
            richTextBox3.LoadFile(path + "\\Resources\\qgk.txt", RichTextBoxStreamType.PlainText);
            //登入提示音
            _sp.Play();

            //启动一个线程，用户监听所有服务器发送来的消息
            startthreads();
        }

       


        /// <summary>
        /// 发送下线消息
        /// </summary>
        private void CloseFrm()
        {

            DialogResult dr = MessageBox.Show("关闭?", "关闭", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr.ToString() == "OK")
            {
                try
                { //发送下线信息
                    ConnectServerSocket.getInstance().getStreamWriter().WriteLine("用户下线|" + Login.userName);
                    ConnectServerSocket.getInstance().getStreamWriter().Flush();
                    ConnectServerSocket.getInstance().closeStream();
                    if (_thread1 != null)
                        _thread1.Abort();
                }
                catch (Exception ex)
                {
                }
                this.Close();
            }
            Application.Exit();
        }


        /// <summary>
        /// 启动Udp服务线程
        /// </summary>
        public void startUdpService()
        {

            Thread MyThread = new Thread(new ThreadStart(this.ReceiveDataFromUDPClient));
            MyThread.IsBackground = true;
            MyThread.Start();

        }

        /// <summary>
        /// 启动Udp服务，接收系统发来的消息
        /// </summary>
        private void ReceiveDataFromUDPClient()
        {
            try
            {
                //Udp接收从服务器发来的信息
                UdpClient MyClient = new UdpClient(32765);
                IPEndPoint MyRemoteEndPoint = null;
                while (true)
                {
                    Byte[] MyData = MyClient.Receive(ref MyRemoteEndPoint);
                    string MyInfo = System.Text.Encoding.Default.GetString(MyData);
                    this.richTextBox2.Text += DateTime.Now.ToLongTimeString() + "=>" + MyInfo + "\n";
                }
            }
            catch (Exception e5)
            {

            }

        }


        /// <summary>
        /// 将图片添加到richTextBox
        /// </summary>
        /// <param name="path">图片的路径</param>
        public void paseImageToRichTextBox(String path)
        {
            Bitmap bitmap1 = new Bitmap(path);
            Clipboard.SetDataObject(bitmap1);
            DataFormats.Format FormatImage = DataFormats.GetFormat(DataFormats.Bitmap);
            if (richTextBox1.CanPaste(FormatImage))
            {
                richTextBox1.Paste(FormatImage);
            }
            else
            {
                MessageBox.Show("表情发送错误！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            bitmap1.Dispose();
        }


        /// <summary>
        /// 让窗体自动适应显示器的分辨率
        /// </summary>
        private void DisplaySettingsChanged()
        {

            if (Convert.ToDouble(Screen.PrimaryScreen.Bounds.Width) < 1440)
            {
                this.Dock = DockStyle.Fill;

            }

        }


        /// <summary>
        /// 建立一个线程复制监听所有服务器发送过来的信息
        /// </summary>
        private void startthreads()
        {
            if (_thread1 == null)
            {
                _thread1 = new Thread(new ThreadStart(StartListeninfo));
                _thread1.Start();

            }
        }


        /// <summary>
        /// 启动tcp服务，接收服务器发来的信息
        /// </summary>
        private void StartListeninfo()
        {
            try
            {
                string[] us = new string[] { };
                while (true)
                {
                    String substr = "";
                    String msg = ConnectServerSocket.getInstance().getStreamReader().ReadLine();
                    us = msg.Split(new char[] { '|' });
                    if (msg.Length >= 4)
                    {
                        substr = msg.Substring(0, 4);
                    }
                    if (substr == "聊天信息")
                    {
                        richTextBox1.AppendText(us[1] + "\t\n" + "   " + us[2] + "\n");
                        writeChatInformation(us[1]);
                        writeChatInformation("    " + us[2]);
                        //消息提示音
                        _sp.Play();
                    }
                    if (substr == "在线人数")
                    {
                        statusBarPanel9.Text = us[1];
                        label2.Text = "[" + us[1] + "]";
                    }
                    if (substr == "全部震动")
                    {
                        _sp2.Play();
                        Nudge();
                    }
                    if (substr == "个人震动")
                    {
                        _sp2.Play();
                        Nudge();
                    }
                    if (substr == "用户列表")
                    {
                        int i = us.Length / 2;//用户数
                        listView_chateronline.Items.Clear();
                        listView_chateronline.Refresh();
                        for (int j = 0; j < i; j++)
                        {
                            listView_chateronline.Items.Add(" ", j);
                            listView_chateronline.Items[j].SubItems.Add(us[2 * j + 1]);
                            listView_chateronline.Items[j].SubItems.Add(us[2 * j + 2]);

                        }
                    }
                    if (substr == "发布公告")
                    {
                        richTextBox3.Text = us[1];
                        //将群公告写在一个文件里面
                        StreamWriter s = new StreamWriter(path + "\\Resources\\qgk.txt", false, Encoding.UTF8);
                        s.WriteLine(us[1]);
                        s.Flush();
                        s.Close();
                    }
                    if (substr == "用户下线")
                    {
                        MessageBox.Show(Convert.ToString(Convert.ToInt16(label2.Text.Substring(0, label2.Text.IndexOf("/"))) - 1));
                         int i = us.Length / 2;//用户数
                        listView_chateronline.Items.Clear();
                        listView_chateronline.Refresh();
                        for (int j = 0; j < i; j++)
                        {
                            listView_chateronline.Items.Add(" ", j);
                            listView_chateronline.Items[j].SubItems.Add(us[2 * j + 1]);
                            listView_chateronline.Items[j].SubItems.Add(us[2 * j + 2]);
                        }
                        
                        string s = Convert.ToString(Convert.ToInt16(label2.Text.Substring(0, label2.Text.IndexOf("/"))) - 1) + "/" + label2.Text.Substring(label2.Text.IndexOf("/") + 1);
                       
                        statusBarPanel9.Text = s;
                        label2.Text = "[" + s + "]";
                    }
                    if (substr == "发送表情")
                    {
                        MessageBox.Show("客户端接收到服务端发送来的图片:"+msg);
                        richTextBox1.AppendText(us[1] + "   " + us[2] + "\n");
                        MessageBox.Show(us[1] + "   " + us[2]);
                        MessageBox.Show(path + "\\newFaces\\" + us[3]);
                       paseImageToRichTextBox(@"D:\My\12.26\12.23\Program\KC_P\newFaces\1.bmp");
                    //    paseImageToRichTextBox(path + "\\newFaces\\" + us[3]);
                        richTextBox1.Refresh();

                       
                    }

                }
            }
            catch (Exception e5) { }
        }


        private void button1_Click(object sender, EventArgs e)
        {
            this.CloseFrm();
        }


        /// <summary>
        /// 产生闪屏振动效果
        /// </summary>
        private void Nudge()
        {
            if (notifyIcon1.Visible == true)
            {
                this.WindowState = FormWindowState.Normal;
            }
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.WindowState = FormWindowState.Normal;
            }
            int i = 0;
            Point _old = this.Location;
            Point _new1 = new Point(_old.X + 3, _old.Y + 3);
            Point _new2 = new Point(_old.X - 3, _old.Y - 3);
            _sp2.Play();
            while (i < 4)
            {
                this.Location = _new1;
                Thread.Sleep(60);
                this.Location = _new2;
                Thread.Sleep(60);
                i++;
            }
            this.Location = _old;
        }


        private void timer1_Tick(object sender, EventArgs e)
        {
            statusBarPanel10.Text = DateTime.Now.ToString();

        }



        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                String Fname;
                saveFileDialog1.Filter = "文本文件(*.txt)|*.txt|doc文件(*.doc)|*.doc";
                saveFileDialog1.FilterIndex = 1;
                saveFileDialog1.Title = "保存文件";
                saveFileDialog1.InitialDirectory = Application.StartupPath;
                saveFileDialog1.RestoreDirectory = true;
                saveFileDialog1.ShowDialog();
                Fname = saveFileDialog1.FileName;
                if (Fname != null)
                {
                    if (saveFileDialog1.FilterIndex == 1)
                    {
                        richTextBox1.SaveFile(Fname, RichTextBoxStreamType.PlainText);
                    }
                    if (saveFileDialog1.FilterIndex == 2)
                    {
                        richTextBox1.SaveFile(Fname, RichTextBoxStreamType.RichText);
                    }

                }
            }
            catch (Exception e5)
            { }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("真的要清除吗?", "温馨提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                richTextBox1.Clear();
                File.Create(path + "ChatHistory.txt").Close();
            }
        }

        private void MsgSend_TextChanged(object sender, EventArgs e)
        {

        }


        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
               /*实现有表情发送的功能
                if (richTextBox4.Text == "")
                {
                    MessageBox.Show("发送内容不能为空!", "温馨提示!");
                }
                if (hasPicture == true)
                {
                        string msg = "发送表情|" + Login.userName + "|说:   " + DateTime.Now.ToLongTimeString() + "|" + pictureName;
                        MessageBox.Show("客户端"+msg);
                        ConnectServerSocket.getInstance().getStreamWriter().WriteLine(msg);
                        ConnectServerSocket.getInstance().getStreamWriter().Flush();
                }
                if (hasPicture == false && richTextBox4.Text!="")
                {
                    String msg = "";
                    if (radioButton1.Checked == true && flag6 == false)
                    {
                        MessageBox.Show("请选择要发送的用户!", "温馨提示!");
                    }
                    if (radioButton2.Checked == true)
                    {
                        //群聊
                        msg = "聊天信息|" + Login.userName + "说:   " + DateTime.Now.ToLongTimeString() + "|" + richTextBox4.Text;
                    }
                    if (radioButton1.Checked == true && flag6 == true)
                    {
                        //单聊
                        msg = "聊天信息|" + Login.userName + "|说:   " + DateTime.Now.ToLongTimeString() + "|" + richTextBox4.Text + "|" + clid;
                    }
                    ConnectServerSocket.getInstance().getStreamWriter().WriteLine(msg);
                    ConnectServerSocket.getInstance().getStreamWriter().Flush();
                }
                richTextBox4.Clear();
                hasPicture = false;
                pictureName = "";
               Clipboard.Clear();
                * */
                 String msg = "";
                 if (richTextBox4.Text == "")
                 {
                     MessageBox.Show("发送内容不能为空!", "温馨提示!");
                 }
                 else
                 {
                     if (radioButton1.Checked == true && flag6 == false)
                     {
                         MessageBox.Show("请选择要发送的用户!", "温馨提示!");
                     }
                     if (radioButton2.Checked == true)
                     {
                         //群聊
                         msg = "聊天信息|" + Login.userName + "说:   " + DateTime.Now.ToLongTimeString() + "|" + richTextBox4.Text;
                     }
                     if (radioButton1.Checked == true && flag6 == true)
                     {
                         //单聊
                         msg = "聊天信息|" + Login.userName + "|说:   " + DateTime.Now.ToLongTimeString() + "|" + richTextBox4.Text + "|" + clid;
                         flag6 = false;
                     }
                     ConnectServerSocket.getInstance().getStreamWriter().WriteLine(msg);
                     ConnectServerSocket.getInstance().getStreamWriter().Flush();
                 }
                 richTextBox4.Clear();
         
            }
            catch (Exception e5) { }

        }

        private void timer2_Tick(object sender, EventArgs e)
        {

        }

        private void pictureBox4_Click(object sender, EventArgs e)
        {
            Bitmap bmp = new Bitmap(Screen.AllScreens[0].Bounds.Width, Screen.AllScreens[0].Bounds.Height);
            Graphics g = Graphics.FromImage(bmp);
            g.CopyFromScreen(0, 0, 0, 0, new Size(Screen.AllScreens[0].Bounds.Width, Screen.AllScreens[0].Bounds.Height));
            frmScreen f = new frmScreen(bmp);
            f.Show();
        }


        /// <summary>
        /// 将聊天信息写入文件
        /// </summary>
        /// <param name="s">聊天内容</param>
        public void writeChatInformation(String s)
        {
            StreamWriter sw = new StreamWriter(path + "ChatHistory.txt", true, Encoding.UTF8);
            sw.WriteLine(s);
            sw.Flush();
            sw.Close();
        }


        /// <summary>
        /// 有新消息来时闪烁任务栏并且保持聊天记录内容滚动到最底端，QQ就是这么玩滴~
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        [DllImport("user32.dll")]
        public static extern bool FlashWindow(IntPtr hWnd, bool bInvert);
        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                FlashWindow(this.Handle, true);
            }
        }


        private void ChatRoom_Load(object sender, EventArgs e)
        {

        }

        private void richTextBox3_TextChanged(object sender, EventArgs e)
        {

        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void ChatRoom_MouseClick(object sender, MouseEventArgs e)
        {
            //启动Udp服务，接受系统发来的消息
            if (flag == false)
            {
                startUdpService();
                flag = true;
            }
        }

        /// <summary>
        ///設置選擇的那個值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listView_chateronline_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                clid = listView_chateronline.SelectedItems[0].SubItems[1].Text;
            }
            catch (Exception e5) { }
        }


        /// <summary>
        /// 当窗口恢复后取消任务栏的闪烁效果
        /// 当窗口最小化时判断是否要隐藏到系统托盘
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 缩到ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            notifyIcon1.Visible = true;
            this.Visible = false;
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {

        }

        /// <summary>
        /// 单击托盘的图标后使它正常显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            notifyIcon1.Visible = false;
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
        }

        private void ChatRoom_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.CloseFrm();
        }


        /// <summary>
        /// 发送闪屏振动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBox7_Click(object sender, EventArgs e)
        {
            String msg="";
            if (radioButton2.Checked == true)
            {
                //向所有人发送震动
                msg = "全部震动|" + Login.userName;
            }
            if (radioButton1.Checked == true && flag6 == true)
            {
                //向所有人发送震动
                msg = "个人震动|" + Login.userName+"|"+clid;
            }
            ConnectServerSocket.getInstance().getStreamWriter().WriteLine(msg);
            ConnectServerSocket.getInstance().getStreamWriter().Flush();

        }





        private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //将双击的图标黏贴到richTextBox1上面，所有获得点击的是那个图标
            string path = Directory.GetCurrentDirectory();
            path = path.Substring(0, path.LastIndexOf("\\"));
            path = path.Substring(0, path.LastIndexOf("\\"));
            path = path + "\\newFaces\\";
            int i = listView1.SelectedItems[0].ImageIndex + 1;
            paseImageToRichTextBox4(path + Convert.ToString(i) + ".bmp");
            hasPicture = true;
            pictureName = Convert.ToString(i) + ".bmp";
            listView1.Visible = false;
        }

        /// <summary>
        /// 将图片添加到richTextBox4
        /// </summary>
        /// <param name="path">图片的路径</param>
        public void paseImageToRichTextBox4(String path)
        {
            Bitmap bitmap1 = new Bitmap(path);
            Clipboard.SetDataObject(bitmap1);
            DataFormats.Format FormatImage = DataFormats.GetFormat(DataFormats.Bitmap);
            if (richTextBox4.CanPaste(FormatImage))
            {
                richTextBox4.Paste(FormatImage);
            }
            else
            {
                MessageBox.Show("表情发送错误！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            bitmap1.Dispose();
        }


        private void pictureBox6_MouseClick(object sender, MouseEventArgs e)
        {
            listView1.Visible = false;
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            if (flag1 == false)
            {
                tempChatInfo = richTextBox1.Text;
                richTextBox1.LoadFile(path + "ChatHistory.txt", RichTextBoxStreamType.PlainText);
                richTextBox1.BackColor = Color.FloralWhite;
                flag1 = true;
            }
            else
            {
                richTextBox1.Text = tempChatInfo;
                richTextBox1.BackColor = Color.White;
                flag1 = false;
            }
        }


        private void 快速回复ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void kingCatToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            new SMS().ShowDialog();
        }

        private void 听听音乐ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new Mp3().Show();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            richTextBox4.Text += comboBox1.SelectedItem.ToString();
        }



        private void pictureBox6_Click(object sender, EventArgs e)
        {
            /*    if (flag5 == false)
                {
                    listView1.Visible = true;
                    flag5 = true;
                }
                else
                {
                    listView1.Visible = false;
                    flag5 = false;
                }
             * */
        }

        private void listView_chateronline_Click(object sender, EventArgs e)
        {
            flag6 = true;
        }

        private void richTextBox4_TextChanged(object sender, EventArgs e)
        {

        }

        private void listView_chateronline_Click_1(object sender, EventArgs e)
        {
            try
            {
                clid = listView_chateronline.SelectedItems[0].SubItems[1].Text;
                flag6 = true;
            }
            catch (Exception e5) { }
        }

        private void pictureBox6_MouseEnter(object sender, EventArgs e)
        {
            listView1.Visible = true;
        }

        private void listView1_MouseLeave(object sender, EventArgs e)
        {
            listView1.Visible = false;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            sel++;
            if (sel == 1)
            {
                richTextBox1.AppendText("KingCat说:    " + DateTime.Now.ToLongTimeString() + "\n");
                paseImageToRichTextBox(@"D:\My\12.26\12.23\Program\KC_P\newFaces\" + sel + ".bmp");
                richTextBox1.AppendText("\n");

            }
            else
            {
                richTextBox1.AppendText("KingCat说    " + DateTime.Now.ToShortTimeString() + "\n");
                paseImageToRichTextBox(@"D:\My\12.26\12.23\Program\KC_P\newFaces\8.bmp");
                richTextBox1.AppendText("\n");
            }
            _sp.Play();
            richTextBox4.Clear();
          
        }

        private void listView_chateronline_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            try
            {
                clid = listView_chateronline.SelectedItems[0].SubItems[1].Text;
                flag6 = true;
            }
            catch (Exception e5) { }
        }
    }
}